import { asyncSetInterval, fixZeroInfo } from '../../lib/zeroReportUtils.js';
import { getinputData } from './data/xqykjzz.js';

const sureBtn = async (iframe) => {
  let num = 0;
  return asyncSetInterval(() => {
    let btn = iframe.querySelector('#ymPrompt_btn_0');
    if (btn) {
      btn.click();
      return true;
    }
    if (num > 3) {
      return true;
    }
    num++;
  }, 1000);
};

let zeroCwbbReprot = async (currentZeroInfo) => {
  let {
    customerType, endPeriod, beginPeriod, year, cwbbInfo, recordList
  } = currentZeroInfo;
  // console.log(customerType, endPeriod, beginPeriod, year);
  asyncSetInterval(async () => {
    if (document.querySelector('#ymPrompt_btn_0')) {
      document.querySelector('#ymPrompt_btn_0').click();
    }
    let date = new Date();
    let day = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
    let begin = beginPeriod > 10 ? beginPeriod : `0${beginPeriod}`;
    let end = endPeriod > 10 ? endPeriod : `0${endPeriod}`;
    document.querySelector('#nsrxxMap_ssqq').set('value', `${year}-${begin}-01`)
      .set('realvalue', `${year}-${begin}-01`)
      .fireEvent('change');
    document.querySelector('#nsrxxMap_ssqz').set('value', `${year}-${end}-${day}`)
      .set('realvalue', `${year}-${end}-${day}`)
      .fireEvent('change');
    if (customerType.includes('小企业会计准则')) {
      document.querySelector('#nsrxxMap_newzlbsdlDm').click();
      let lis = document.querySelectorAll('#nsrxxMap_newzlbsdlDm_sl > div.swordselect-list-inner > div');
      let xqykjzz = Array.from(lis).find(item => item.innerHTML.includes('小企业会计准则'));
      xqykjzz.click();
      document.querySelector('#nsrxxMap_newzlbszlDm').click();
      await asyncSetInterval(() => {
        let lis1 = document.querySelectorAll('#nsrxxMap_newzlbszlDm_sl > div.swordselect-list-inner > div');
        let xqykjzz1 = Array.from(lis1).find(item => item.innerHTML.includes('小企业会计准则'));
        xqykjzz1.click();
        return true;
      }, 500).then(() => {
        document.querySelector('#nsrxxMap_newzlbsxlDm').click();
        let lis1 = document.querySelectorAll('#nsrxxMap_newzlbsxlDm_sl > div.swordselect-list-inner > div');
        let xqykjzz1 = Array.from(lis1).find(item => item.innerHTML.includes('小企业会计准则'));
        xqykjzz1.click();
        return true;
      }).then(() => {
        return asyncSetInterval(() => {
          let divs = document.querySelectorAll('#main > div:nth-child(4) > div.sGrid_div > div:nth-child(2) > div.sGrid_data_div > div');
          if (divs.length) {
            let bixus = Array.from(divs).filter(item => !item.innerHTML.includes('年报'));
            bixus.forEach(item => {
              let input = item.querySelector('input[name="sftj"]');
              console.log(input);
              if (!parseInt(input.value)) input.click();
            });
            return asyncSetInterval(() => {
              document.querySelector('#buttons > tbody > tr > td > div').click();
              return true;
            }, 1000);
          }
        }, 1000);
      }).then(() => {
        return asyncSetInterval(() => {
          if (document.querySelector('#ymPrompt_btn_0')) {
            document.querySelector('#ymPrompt_btn_0').click();
          }
          return true;
        }, 2000);
      })
        .then(() => {
          let divs = [];
          let idocumnet = null;
          let iwin = null;
          if (document.querySelector('#ymPrompt_btn_0')) {
            document.querySelector('#ymPrompt_btn_0').click();
          }
          return asyncSetInterval(() => {
            if (document.querySelector('#ymPrompt_btn_0')) {
              document.querySelector('#ymPrompt_btn_0').click();
            }
            let iframe = document.querySelector('#allframe > div > div.x-tab-panel-body > iframe');
            if (iframe) {
              idocumnet = iframe.contentDocument;
              iwin = iframe.contentWindow;
            }
            if (idocumnet) {
              let tabs = idocumnet.querySelectorAll('.tree-select-list > div > div > div');
              if (tabs.length) {
                tabs = Array.from(tabs).find(item => item.style.display !== 'none');
                if (tabs) {
                  divs = tabs.querySelectorAll('div.tree-node');
                  if (divs.length) {
                    console.log(divs);
                    return true;
                  }
                }
              }
            }
          }, 2000).then(() => {
            let num = 0;
            return asyncSetInterval(() => {
              if (idocumnet.querySelector('#ymPrompt_btn_0')) {
                idocumnet.querySelector('#ymPrompt_btn_0').click();
              }
              if (num > 2) {
                return true;
              }
              num++;
            }, 1000);
          }).then(() => {
            let tree = iwin.$w('SwordTreeJSON');
            let nodes = tree.getAllNode();
            // 资产负债表
            iwin.openTab(nodes[3]);
            return asyncSetInterval(() => {
              let iframe = idocumnet.querySelector('#table00iframe').contentDocument;
              let data = getinputData(cwbbInfo.zcfzb, 'xqykjzz', 'balance', false, true);
              let systmDate = false;
              let shuijuDate = false;
              data.forEach(({ key, value = 0 }) => {
                let input = iframe.querySelector(`#${key}`);
                if (parseInt(input.value)) shuijuDate = true;
                if (parseInt(value)) systmDate = true;
              });
              if (systmDate) {
                data.forEach(({ key, value = 0 }) => {
                  let input = iframe.querySelector(`#${key}`);
                  input.set('value', value || 0)
                    .set('realvalue', value || 0)
                    .fireEvent('change');
                });
              } else if (!systmDate && !shuijuDate) {
                ['zcfzbxxForm_h9l2', 'zcfzbxxForm_h9l3', 'zcfzbxxForm_h29l5', 'zcfzbxxForm_h29l6'].forEach((key) => {
                  let input = iframe.querySelector(`#${key}`);
                  input.set('value', 0.01)
                    .set('realvalue', 0.01)
                    .fireEvent('change');
                });
              }
              return iframe;
            }, 1000).then((iframe) => {
              return asyncSetInterval(() => {
                let save = iframe.querySelector("#wtdzsb > div.tb_mini_box > div.c > div[name='save']");
                if (save) {
                  save.click();
                  return true;
                }
              }, 1000).then(async () => {
                await sureBtn(iframe);
                await sureBtn(idocumnet);
                return true;
              });
            }).then(() => {
              iwin.openTab(nodes[4]);
              // 利润表
              return asyncSetInterval(() => {
                let iframe = idocumnet.querySelector('#table01iframe').contentDocument;
                let data = getinputData(cwbbInfo.lrb, 'xqykjzz', 'profit', false, true);
                data.forEach(({ key, value = 0 }) => {
                  let input = iframe.querySelector(`#${key}`);
                  input.set('value', value || 0)
                    .set('realvalue', value || 0)
                    .fireEvent('change');
                });
                return iframe;
              }, 1000).then((iframe) => {
                return asyncSetInterval(() => {
                  let save = iframe.querySelector("#wtdzsb > div.tb_mini_box > div.c > div[name='save']");
                  if (save) {
                    save.click();
                    return true;
                  }
                }, 1000).then(async () => {
                  await sureBtn(iframe);
                  await sureBtn(idocumnet);
                  return true;
                });
              });
            }).then(() => {
              iwin.openTab(nodes[5]);
              // 现金流量表
              return asyncSetInterval(() => {
                let iframe = idocumnet.querySelector('#table02iframe').contentDocument;
                let data = getinputData(cwbbInfo.xjllb, 'xqykjzz', 'cash', false, true);
                data.forEach(({ key, value = 0 }) => {
                  let input = iframe.querySelector(`#${key}`);
                  input.set('value', value || 0)
                    .set('realvalue', value || 0)
                    .fireEvent('change');
                });
                return iframe;
              }, 1000).then((iframe) => {
                return asyncSetInterval(() => {
                  let save = iframe.querySelector("#wtdzsb > div.tb_mini_box > div.c > div[name='save']");
                  if (save) {
                    save.click();
                    return true;
                  }
                }, 1000).then(async () => {
                  await sureBtn(iframe);
                  await sureBtn(idocumnet);
                  return true;
                });
              });
            })
              .then(() => {
                return asyncSetInterval(() => {
                  let submit = document.querySelector('#cwsb11');
                  submit.click();
                  return true;
                }, 1000);
              })
              .then(() => {
                return asyncSetInterval(() => {
                  let iframe = document.querySelector('#allframe > div > div.x-tab-panel-body > iframe').contentDocument;
                  if (iframe) {
                    let btn = iframe.querySelector('#ymPrompt_btn_0');
                    let info = iframe.querySelector('#ym-ml .ym-content');
                    if (btn && info.innerText.includes('采集成功')) {
                      btn.click();
                      let cwbbItem = recordList.find(item => item.declareName.includes('财务报表资料报送与采集'));
                      cwbbItem.isSuccess = true;
                      fixZeroInfo({ recordList: [cwbbItem] });
                      setTimeout(() => {
                        window.location.href = 'https://etax.chongqing.chinatax.gov.cn/sword?ctrl=WBLoginGdgjCtrl_openLayout3Win';
                      }, 1000);
                      return true;
                    }
                    console.log('申报错误，请联系管理员');
                  }
                }, 1000);
              });
          });
        });
      return true;
    }
  }, 2000);
};

export {
  zeroCwbbReprot
};
